from socket import *
from threading import Thread


class Handle(Thread):
    def __init__(self, conn, addr, html):
        self.conn = conn
        self.address = addr
        self.html = html
        super().__init__()

    def run(self):
        request = self.conn.recv(1024)
        if not request:
            self.conn.close()
            return
        info = request.decode().split(" ")[1]
        print(info)
        response = self._response(info)
        self.conn.send(response)

    def _response(self, info):
        if info == "/":
            info = "/index.html"
        try:
            with open(self.html+info, "rb") as fr:
                data = fr.read()
        except:
            with open(self.html+"404.html", "rb") as fr:
                data = fr.read()
        response = b"HTTP/1.1 200 OK \r\n"
        response += b"Content-Type: text/html\r\n"
        response += b"\r\n"
        response += data
        return response


class ThreadServer:
    def __init__(self, host="", port=0, html=None):
        self.host = host
        self.port = port
        self.html = html
        self.address = (host, port)
        self.sock = self._create_socket()

    def _create_socket(self):
        sock = socket()
        sock.bind(self.address)
        return sock

    # 启动服务
    def serve_forever(self):
        self.sock.listen()
        print("Listen the port :", self.port)
        while True:
            conn, addr = self.sock.accept()
            print("Connect from :", addr)
            t = Handle(conn, addr, self.html)
            t.start()


if __name__ == '__main__':
    httpd = ThreadServer(host="0.0.0.0", port=8888, html="/home/u/Downloads/static")
    httpd.serve_forever()
